class ReviewsController < ApplicationController
  before_filter :login_required, :only => [:new]
  require 'rubygems'
  require 'qype'
  require "rexml/document"
  require "oauth/consumer"
  include REXML


  def index
    #request = session[:access_token].request(:get, "http://api.qype.com/v1/places/#{params[:id]}/reviews?order=date_created")
    qype = Qype::Client.new(MyQype::API_KEY, MyQype::API_SECRET)
    request = qype.get("http://api.qype.com/v1/places/#{params[:id]}/reviews?order=date_created")
    @reviews = Qype::Review.parse(request.body)
  end

  def new
    @review = Review.new()
  end

  def create

    @review = Review.new(params[:review])

    builder = Nokogiri::XML::Builder.new(:encoding => 'UTF-8') do |xml|
      xml.review {
        xml.language @review.language
        xml.rating @review.rating
        xml.tag(:scheme => "http://api.qype.com/v1/tags", :term => @review.tag)
        xml.content(:type => "text") do
          xml.cdata @review.content
        end
      }
    end

    #puts builder.to_xml
    
    if @review.valid?
      # sandbox place id: 537582
      @response = session[:access_token].post('http://api.qype.com/v1/places/537582/reviews',builder.to_xml,{'Content-Type'=>'application/xml'})
      puts @response.body
      
      flash[:notice] = "Successfully created review."
      redirect_to root_url
    else
      render :action => 'new'
    end

  end

end
